package com.gdsunfly.mongodb.service.impl;

import com.gdsunfly.mongodb.pojo.entity.Person;
import com.gdsunfly.mongodb.repository.PersonRepository;
import com.gdsunfly.mongodb.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


import java.util.List;

/**
 * @author gdsunfly_wangquanqing
 * @date 2019/6/12 17:27
 */
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void testTransactional(Person person,Boolean isRollback) {

//            mongoTemplate.insert(person);
            personRepository.insert(person);

            if (isRollback) {
                // 这里会抛出空指针
                person = null;
                person.getAge();
            }

        // 如果有捕获异常，则必须加一行代码，否则发生异常时还是能insert到数据库；加了后才能回滚insert操作。
        // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

    }
}
